package com.hzdl.sbdemo.util;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
public class HzdlExceptionHandler {


    /**
     * 出现异常的处理方法
     *
     * @param request  请求
     * @param response 响应
     * @param e  异常
     * @return ajax 返回的是HzdlAjaxResult 对象， 页面返回是ModelAndView对象
     */
    @ExceptionHandler(value = Exception.class)
    public Object handler(HttpServletRequest request, HttpServletResponse response , Exception e){
        System.out.println("异常出现了");

        //X-Requested-With: XMLHttpRequest
        // 获取头部请求
       String header =  request.getHeader("X-Requested-With");
       if(header != null && "XMLHttpRequest".equals(header)){
           // ajax请求
           return  new HzdlAjaxResult(-1,e.getMessage(),null);
       }else{
           // 页面请求
           ModelAndView mav = new ModelAndView();
           mav.setViewName("error");
           mav.addObject("msg",e.getMessage());
           return mav;
       }


    }


}
